using System.Collections.Generic;
using UnityEngine;

public class GridMap : MonoBehaviour
{
    public int Col = 10;
    public int Row = 10;
    public float Width = 0.1f;
    public float Height = 0.1f;
    public Vector3 StartPos = default;
    public GameObject GridPrefab;
    private List<GameObject> grid = new List<GameObject>();
    private Dictionary<long, GameObject> grids = new Dictionary<long, GameObject>();
    Grid BeginGrid = null;
    Grid EndGrid = null;

    Dijkstra DijkstraPathFinder = new Dijkstra();

    private void Awake()
    {
        Grid.Width = Width;
        Grid.Height = Height;
        var worldScreenOri = Camera.main.ScreenToWorldPoint(transform.position);
        StartPos += worldScreenOri;
        StartPos.z = 100;
        Debug.Log($"Wrold Origin: {worldScreenOri.x}, {worldScreenOri.y}, {worldScreenOri.z}");
        System.Random rand = new System.Random();
        int count = Col * Row;
        for (int i = 0; i < Row; ++i)
            for (int j = 0; j < Col; ++j)
            {
                if (Random.Range(0, count) > count / 5)
                {
                    var g = CreateGrid(i, j);
                    grid.Add(g);
                    grids.Add(i * 10000 + j, g);
                }
            }
    }

    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
    }

    public bool CommitGrid(Grid grid)
    {
        if (null == BeginGrid)
        {
            Reset();
            BeginGrid = grid;
            return true;
        }

        if (null == EndGrid)
        {
            EndGrid = grid;
            // logic
            var result = DijkstraPathFinder.PathFind(BeginGrid, EndGrid, grids);
            foreach (var id in result)
            {
                if (grids.TryGetValue(id, out var obj) && id != BeginGrid.Id)
                {
                    obj.GetComponent<MeshRenderer>().material.color = Color.yellow;
                }
            }

            BeginGrid = null;
            EndGrid = null;
            return true;
        }
        return false;
    }

    private void Reset()
    {
        foreach (var g in grid)
        {
            var g1 = g.GetComponent<Grid>();
            if (null != g1)
                g1.Reset();
        }
    }

    private GameObject CreateGrid(int row, int col)
    {
        var go = GameObject.Instantiate(GridPrefab, transform);
        Grid grid = go.GetComponent<Grid>();
        grid.Parent = this;
        grid.Row = row;
        grid.Col = col;

        float posX = StartPos.x + Grid.Width * col + Grid.Width / 2;
        float posY = StartPos.y + Grid.Height * row + Grid.Height / 2;
        go.transform.position = new Vector3(posX, posY, 100);
        //Debug.Log($"{row}:{col} : {row * 10000 + col}=> x: {posX}, y:{posY}");
        return go;
    }
}
